var WebIM = {};

WebIM.Emoji = {
    path: '../../image/chat/emoji/',
    map: {
        '[:A)]': 'aini.png',
        '[:B)]': 'bishi.png',
        '[:C)]': 'bizui.png',
        '[:D)]': 'bulini.png',
        '[:E)]': 'daku.png',
        '[:F)]': 'deyi.png',
        '[:G)]': 'gaxiao.png',
        '[:H)]': 'jiaxiao.png',
        '[:I)]': 'kaixin.png',
        '[:J)]': 'keai.png',
        '[:K)]': 'liuhan.png',
        '[:L)]': 'liuhan_1.png',
        '[:M)]': 'nanguo.png',
        '[:N)]': 'nanshou.png',
        '[:O)]': 'se.png',
        '[:P)]': 'weixiao.png',
        '[:Q)]': 'xiaoku.png',
        '[:R)]': 'xiudaliao.png',
        '[:S)]': 'yukuai.png',
        '[:T)]': 'zhiqi.png',
    }
};

//创建文本消息
function createTextMsg(user, message, isMe) {
    var icon = user.icon;
    var name = user.name;
    var tags = user.tags;
    var time = timestampToTime(message.timestamp);
    var msg = message.body.text;
    var itemTag = "";
    for (var i = 0; i < tags.length; i++) {
        itemTag += "<span class=\"msg-idcard\">" + tags[i] + "</span>";
    }
    var item = "<div contenteditable='true' class='" + (isMe ? 'item item-myself' : 'item') + "'>" +
        "<div class=\"mentor-msg-top\">" +
        "<span class=\"msg-img\"><img src='" + icon + "' alt=\"\"></span>" +
        "<span class=\"msg-name\">" + name + "</span>" + itemTag +
        "<span class=\"msg-time\">" + time + "</span>" +
        "</div>" +
        "<div class=\"mentor-msg-txt clipper\"><p>" + parseEmoji(msg) + "</p></div>" +
        "</div>";

    return item;
}

//创建图片消息
function createImgMsg(user, message, isMe) {
    var icon = user.icon;
    var name = user.name;
    var tags = user.tags;
    var time = timestampToTime(message.timestamp);
    var img = message.body.remotePath;
    var itemTag = "";
    for (var i = 0; i < tags.length; i++) {
        itemTag += "<span class=\"msg-idcard\">" + tags[i] + "</span>";
    }
    return " <div class='" + (isMe ? 'item item-myself' : 'item') + "'>\n" +
        "<div class=\"mentor-msg-top\">\n" +
        "<span class=\"msg-img\"><img src='" + icon + "' alt=\"\"></span>\n" +
        "<span class=\"msg-name\">" + name + "</span>\n" + itemTag +
        "<span class=\"msg-time\">" + time + "</span>\n" +
        " </div>\n" +
        "<div class=\"mentor-msg-txt\">\n" +
        "<img data-preview-src src='" + img + "' class=\"img-style\">\n" +
        "</div>\n" +
        "</div>";
}

/**
 * 创建语音消息
 * @param user 用户信息
 * @param message 消息内容
 * @param isRead 是否已读
 * @param isMe 是否是我发起
 * @returns {string}
 */
function createVoiceMsg(user, message, isMe) {
    var icon = user.icon;
    var name = user.name;
    var tags = user.tags;
    var time = timestampToTime(message.timestamp);
    var messageId = message.messageId;
    var voicePath = message.body.remotePath;
    var localPath = message.body.localPath;
    var voiceTime = message.body.duration;
    var displayName = message.body.displayName;
    var itemTag = "";
    var isRead = msgIsRead(conversationId, myRingName, message.messageId) || isMe;
    for (var i = 0; i < tags.length; i++) {
        itemTag += "<span class=\"msg-idcard\">" + tags[i] + "</span>";
    }
    var audioItem;
    // if (isMe) {
    audioItem = "<button class=\"voice mentor-msg-txt\" style='background: transparent' isRead='"+isRead+"' onclick='play(this,\"" + messageId + "\",\"" + voicePath + "\",\"" + localPath + "\",\"" + displayName + "\"," + isRead + ")'><p style='pointer-events:none;max-width: 15em;width:" + (5 + voiceTime * 0.5) + "em; text-align:" + (isMe ? "right" : "left") + "'>" + voiceTime + "<i class='gificon'></i><span  class='" + (isRead ? '' : 'redpoint') + "'></span> </p>\n" +
        "</button>\n";
    // } else {
    //     audioItem = "<button class=\"mentor-msg-txt\" style='background: transparent'  onclick='play(\"" + voicePath + "\",\"" + localPath + "\",\"" + displayName + "\")'><p  style='pointer-events:none;max-width: 15em;width:" + (5 + voiceTime * 0.5) + "em; text-align: left'>"+voiceTime+"<i class='gificon'></i> </p>\n" +
    //         "</button>\n";
    // }
    return " <div class='" + (isMe ? 'item item-myself' : 'item') + "'>\n" +
        "                        <div class=\"mentor-msg-top\">\n" +
        "                            <span class=\"msg-img\"><img src='" + icon + "' alt=\"\"></span>\n" +
        "                            <span class=\"msg-name\">" + name + "</span>\n" + itemTag +
        "                            <span class=\"msg-time\">" + time + "</span>\n" +
        "                        </div>\n" +
        audioItem +
        "                    </div>";
}
var currentVoice;
var currentVoiceMsgId;
var isPlay=false;
/**
 * 语音播放
 * @param content 上下文对象
 * @param path 下载路径
 * @param localPath 本地路径
 * @param displayName 文件名称
 * @param messageId 消息id
 * @param isRead 是否已读
 */
function play(content, messageId, path, localPath, displayName, isRead) {
    api.stopPlay();
    if (currentVoice !== undefined)
        $(currentVoice).find('i').removeClass('voicePlay');
    currentVoice = content;
    if(isPlay && currentVoiceMsgId===messageId){
        isPlay=false;
        return;
    }
    currentVoiceMsgId=messageId;
    $(currentVoice).find('span').removeClass('redpoint');
    $(content).attr("isRead","true");
    if (!isRead) {
        //将未读消息存入本地数据库
        markRead(conversationId, myRingName, messageId);
    }
    //检测本地路径是否存在
    var fs = api.require('fs');
    fs.exist({
        path: localPath
    }, function (ret, err) {
        if (ret.exist) {
            $(content).find('i').addClass('voicePlay');
            isPlay=true;
            api.startPlay({
                path: localPath
            }, function (ret, err) {
                isPlay=false;
                $(content).find('i').removeClass('voicePlay');
                autoPlay(content);
            });
        } else {
            api.download({
                url: path,
                savePath: 'fs://cache/audio/' + displayName
            }, function (ret, err) {
                //coding...
                if (ret.state === 1) {
                    $(content).find('i').addClass('voicePlay');
                    isPlay=true;
                    api.startPlay({
                        path: 'fs://cache/audio/' + displayName
                    }, function (ret, err) {
                        isPlay=false;
                        $(content).find('i').removeClass('voicePlay');
                        autoPlay(content);
                    });
                }
            });
        }
    });
    // }
}
function autoPlay(content) {
    var isAutoPlay=false;
    $('.voice').each(function (index) {
        if(this===content){
            //找到当前播放语音位置，在开始查询
            isAutoPlay=true;
        }
        if(isAutoPlay && $(this).attr('isRead')==="false"){
            $(this).click();
            return false;
        }
    });
    return false;
}
//创建文件消息
function createFileMsg(user, message, isMe) {
    var icon = user.icon;
    var name = user.name;
    var tags = user.tags;
    var time = timestampToTime(message.timestamp);
    var fileName = message.body.displayName;
    var remotePath = message.body.remotePath;
    var localPath = message.body.localPath;
    var messageId = message.timestamp;
    var itemTag = "";
    for (var i = 0; i < tags.length; i++) {
        itemTag += "<span class=\"msg-idcard\">" + tags[i] + "</span>";
    }

    var item = "<div class='" + (isMe ? 'item item-myself' : 'item') + "'>\n" +
        "                        <div class=\"mentor-msg-top\">\n" +
        "                            <span class=\"msg-img\"><img src='" + icon + "' alt=\"\"></span>\n" +
        "                            <span class=\"msg-name\">" + name + "</span>\n" + itemTag +
        "                            <span class=\"msg-time\">" + time + "</span>\n" +
        "                        </div>\n" +
        "                        <!-- 发文件 -->\n" +
        "                        <div class=\"mentor-msg-txt\">\n" +
        "                            <div class=\"card-body\">\n" +
        "                                <div>\n" +
        "                                    <h2>文件</h2>\n" +
        "                                    <span><h3>" + fileName + "</h3></span>\n" +
        "                                    <div id='file_" + messageId + "' class=\"card-bottom clearfix\">\n" +
        "                                    </div>\n" +
        "                                </div>\n" +
        "                            </div>\n" +
        "                        </div>\n" +
        "                    </div>";
    exists('file_' + messageId, fileName, "file", localPath, remotePath);
    return item;
}

function createVideoMsg(user, message, isMe) {
    var name = user.name;
    var icon = user.icon;
    var tags = user.tags;
    var time = timestampToTime(message.timestamp);
    var fileName = message.body.displayName;
    var remotePath = message.body.remotePath;
    var messageId = message.timestamp;
    var itemTag = "";

    for (var i = 0; i < tags.length; i++) {
        itemTag += "<span class=\"msg-idcard\">" + tags[i] + "</span>";
    }
    var item = "<div class='" + (isMe ? 'item item-myself' : 'item') + "'>\n" +
        "                        <div class=\"mentor-msg-top\">\n" +
        "                            <span class=\"msg-img\"><img src='" + icon + "' alt=\"\"></span>\n" +
        "                            <span class=\"msg-name\">" + name + "</span>\n" + itemTag +
        "                            <span class=\"msg-time\">" + time + "</span>\n" +
        "                        </div>\n" +
        "                        <!-- 发视频 -->\n" +
        "                        <div  class=\"mentor-msg-txt\">\n" +
        "                            <div id='video_" + messageId + "' style='position: relative;width: 240px;height:160px'>\n" +
        "                            </div>\n" +
        "                        </div>\n" +
        "                    </div>";
    exists("video_" + messageId, fileName, "video", message.body.localPath, remotePath);
    return item;
}

function openFile(localPath) {
    api.alert({
        title: "提示",
        msg: "文件已保存至:" + localPath
    });
    // console.log(api.fsDir);
    // api.openApp({
    //     androidPkg: 'android.intent.action.VIEW',
    //     mimeType: 'image/*',
    //     uri: "content:///" + api.fsDir + "/login_btn.png"
    //     // uri: 'file:///storage/emulated/0/UZMap/A6947555569146/cache/video/1.mp4'
    // }, function (ret, err) {
    //     console.log(JSON.stringify(err) + "," + JSON.stringify(ret));
    // });
}

/**
 * 检测文件是否存在并下载
 * @param id itemId
 * @param name 文件名字
 * @param remotePath  下载地址
 * @param localPath 本地地址
 * @param type 文件类型
 */
function exists(id, name, type, localPath, remotePath) {
    var fs = api.require('fs');
    //检测本地路径是否存在
    fs.exist({
        path: localPath
    }, function (ret, err) {
        if (!ret.exist) {
            //检测本地缓存是否存在
            var dir;
            if (type === "video") {
                dir = "/video/";
            } else if (type === "file") {
                dir = "/file/";
            }
            fs.exist({path: "fs://cache" + dir + name}, function (ret, err) {
                if (type === "video") {
                    showVideo(id, name, ret.exist ? api.fsDir + "/cache" + dir + name : remotePath, ret.exist);
                } else if (type === "file") {
                    showFile(id, name, ret.exist ? api.fsDir + "/cache" + dir + name : remotePath, ret.exist);
                }
            })
        } else {
            if (type === "video") {
                showVideo(id, name, localPath, true);
            } else if (type === "file") {
                showFile(id, localPath, true);
            }
        }
    });
}

function showFile(id, name, path, isExist) {
    if (isExist)
        $('#' + id).append("<button onclick = 'openFile(\"" + path + "\")'> 查看</button>");
    else
        $("#" + id).append("<button onclick = 'downloadFile(\"" + id + "\",\"" + name + "\",\"" + path + "\")'> 点击下载</button>");
}

function showVideo(id, name, path, isExist) {
    if (isExist) {
        // $('#' + id).append("<video id='video'  style='width: 240px;height: 160px'  controls>\n" +
        //     "<source src=\"" + path + "\" type=\"video/mp4 \"/>\n" +
        //     "</video>");
        getSmallVideoImg(id, name, path);
    } else {
        $('#' + id).append("<div style='text-align:center;line-height:160px;position: absolute;top: 0;background: black;width: 240px;height:160px '><p style='vertical-align: middle'>播放</p></div>");
        api.download({
            url: path,
            report: true,
            savePath: "fs://cache/video/" + name
        }, function (ret, err) {
            //coding...
            if (ret.state === 0) {
                //下载中
                $('#' + id).find('div').find('p').text(ret.percent + "%");
            } else if (ret.state === 1) {
                //下载成功
                // $('#' + id).html("<video  style='width: 240px;height: 160px'  controls>\n" +
                //     "<source src=\"" + api.fsDir + "/cache/video/" + name + "\" type=\"video/mp4 \"/>\n" +
                //     "</video>");
                getSmallVideoImg(id, name, api.fsDir + "/cache/video/" + name);
            }else {
                $('#' + id).find('div').find('p').text("加载失败");
            }
        });
    }
}

function getSmallVideoImg(id, name, path) {
    var videoScreenshots = api.require('videoScreenshots');
    videoScreenshots.screenshots({
        videoUrl: path,
        time: 1,
        isRotation:false,
        name: name
    }, function (ret) {
        console.log(JSON.stringify(ret));
        if (ret.status) {
            $('#' + id).append("<div  style='position:relative;width: 240px;height: 3rem;'><img src='"+ret.path+"' style='width: 100%;height: 100%;'/><button style='width:75px;height: 75px;background-image:url(../../image/video_play.png);background-repeat: no-repeat; background-size: 100% 100%;background-color:transparent;position: absolute;top: 50%;left: 50%;transform:translate(-50%,-50%);  ' onclick='openVideo(\"" + path + "\")'></button></div>");
            // $('#' + id).append("<button style='width: 240px;height: 240px;background: url("+ret.path+") no-repeat center;background-size: 100% 100%' onclick='openVideo(\"" + path + "\")'/>");
            // $('#' + id).find('video').attr("poster", ret.path);
        }
    });
}

function parseEmoji(e) {
    if (void 0 === WebIM.Emoji || void 0 === WebIM.Emoji.map) return e;
    var t = WebIM.Emoji;
    for (var r in t.map) if (t.map.hasOwnProperty(r)) for (; e.indexOf(r) > -1;) e = e.replace(r, '<img class="emoji" style="vertical-align:text-bottom;border: none;width: 16px;height: 16px" src="' + t.path + t.map[r] + '" />');
    return e
}

function downloadFile(id, name, path) {
    console.log(path);
    $('#' + id).html("<button> 下载中...</button>");
    api.download({
        url: path,
        report: true,
        savePath: "fs://cache/file/" + name
    }, function (ret, err) {
        console.log(JSON.stringify(ret));
        if (ret.state) {
            var localPath = api.fsDir + "/cache/file/" + name;
            $('#' + id).html("<button onclick = 'openFile(\"" + localPath + "\")'> 查看</button>");
        }
    });
}

function timestampToTime(timestamp) {
    //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    if ((timestamp + "").length <= 10)
        timestamp *= 1000;
    var date = new Date(timestamp);
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = date.getDate();
    h = date.getHours() + ':';
    m = date.getMinutes();
    s = date.getSeconds();
    var currentDate = new Date();
    var currentM = (currentDate.getMonth() + 1 < 10 ? '0' + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1);
    var currentD = currentDate.getDate();
    var showTime = '';
    if (currentM !== M || currentD !== D) {
        showTime = M + "月" + D + '日 ';
    }
    if ((h + "").length === 2) {
        h = "0" + h;
    }
    if ((m + "").length === 1) {
        m = "0" + m;
    }
    return showTime + h + m;
}
